﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using User.Identity.Services;

namespace User.Identity.Authentication
{
    public class SmsAuthCodeValidator
        : IExtensionGrantValidator
    {
        private readonly IUserService _userService;
        private readonly IAuthCodeService _smsAuthCodeService;
        public SmsAuthCodeValidator(IUserService userService, IAuthCodeService smsAuthCodeService)
        {
            _userService = userService;
            _smsAuthCodeService = smsAuthCodeService;
        }
        public string GrantType => "sms_auth_code";

        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            //TDB
            var phone = context.Request.Raw["phone"];
            var authCode = context.Request.Raw["auth_code"];
            var errorGrantResult = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
            if (string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(authCode))
            {
                context.Result = errorGrantResult;
                return;
            }
            if (!await _smsAuthCodeService.Validate(phone, authCode))
            {
                context.Result = errorGrantResult;
                return;
            }
            var user = await _userService.CheckOrCreatePhoneAsync(phone);
            if (user != null)
            {
                var claims = new List<Claim>() {
                     new Claim("name", user.Name),
                     new Claim("avatar", user.Avatar),
                     new Claim("company", user.Company),
                     new Claim("title", user.Title),
                     new Claim("id", user.Id.ToString())
                };
                context.Result = new GrantValidationResult(user.Id.ToString(), GrantType, claims:claims);
            }
        }
    }
}
